package com.bc.trade.channel.wmyl;

import java.util.Map.Entry;
import java.util.TreeMap;

import com.alibaba.fastjson.JSONObject;
import com.bc.common.CommonEnum.OrderStatus;
import com.bc.common.CommonEnum.Resp;
import com.bc.common.message.DFReq;
import com.bc.common.message.DFResp;
import com.bc.trade.channel.IChannel;
import com.bc.trade.config.SystemConfig;
import com.bc.trade.message.QueryCardInfoReq;
import com.bc.trade.message.QueryCardInfoResp;
import com.bc.trade.message.QueryOrderResp;
import com.bc.trade.message.QuickPayReq;
import com.bc.trade.message.QuickPayResp;
import com.bc.trade.message.QuickPaySetReq;
import com.bc.trade.message.QuickPaySetResp;
import com.bc.trade.message.RefundReq;
import com.bc.trade.message.RefundResp;
import com.bc.trade.message.SendSMSReq;
import com.bc.trade.message.SendSMSResp;
import com.bc.trade.message.UnionPayReq;
import com.bc.trade.message.UnionPayResp;
import com.bc.trade.model.TradeOrder;
import com.fs.common.util.FSHttp;
import com.fs.common.util.FSLog;
import com.fs.common.util.FSMD5;
import com.fs.common.util.FSString;
import com.jfinal.config.Constants;
import com.jfinal.kit.StrKit;

public class WmylChannel implements IChannel {
	private final String MERCHANT_NO = SystemConfig.channelConfig.get("wmyl_merchant_no");
	private final String KEY = SystemConfig.channelConfig.get("wmyl_key");
	private final String TRADE_URL = SystemConfig.channelConfig.get("wmyl_trade_url");
	private final String TRADE_QUERY_URL = SystemConfig.channelConfig.get("wmyl_trade_query_url");
	private final String TRADE_NOTIFY_URL = SystemConfig.channelConfig.get("wmyl_trade_notify_url");
	private final String DF_URL = SystemConfig.channelConfig.get("wmyl_df_url");
	private final String DF_QUERY_URL = SystemConfig.channelConfig.get("wmyl_df_query_url");
	private final String DF_NOTIFY_URL = SystemConfig.channelConfig.get("wmyl_df_notify_url");
	
	@Override
	public UnionPayResp unionpay(UnionPayReq req, TradeOrder order) throws Exception {
		UnionPayResp resp = new UnionPayResp(req);
		TreeMap<String, String> reqMap = new TreeMap<String, String>();
		reqMap.put("merchantNo", MERCHANT_NO);
		reqMap.put("orderNo", order.getOrderNo());
		reqMap.put("trxAmt", order.getAmount().toString());
		reqMap.put("productDesc", "商品收银");
		reqMap.put("bankCode", req.getBankType());
		reqMap.put("notifyUrl", TRADE_NOTIFY_URL);
		reqMap.put("showUrl", req.getCallbackUrl());
		String signStr = postString(reqMap);
		reqMap.put("sign", FSMD5.codeFor(signStr + KEY).toUpperCase());
		String content = FSString.convertMapToUrlParameter(reqMap);
		FSLog.api.info("WMYL网银交易请求数据" + content);
		try {
			String resultStr = FSHttp.postFormString(TRADE_URL, content, "UTF-8");
			FSLog.api.info("WMYL网银交易响应数据" + resultStr);
			if (StrKit.notBlank(resultStr)) {
				JSONObject returnObj = JSONObject.parseObject(resultStr);
				String respCode = returnObj.getString("respCode");
				if ("0000".equals(respCode)) {
					resp.setCodeAndMsg(Resp.Success.getCode(), Resp.Success.getMsg());
					resp.setHtml(returnObj.getString("html"));
					resp.setType("0");
				} else {
					resp.setCodeAndMsg(Resp.Fail.getCode(), Resp.Fail.getMsg());
					resp.setType("0");
					resp.setHtml("");
				}
			} else {
				resp.setCodeAndMsg(Resp.Fail.getCode(), Resp.Fail.getMsg());
				resp.setHtml("");
			}
		} catch(Exception e) {
			FSLog.api.error("WMYL交易发起异常" + e);
			resp.setCodeAndMsg(Resp.Fail.getCode(), Resp.Fail.getMsg());
		} 
		
		return resp;
	}

	@Override
	public QueryOrderResp query(TradeOrder order) throws Exception {
		QueryOrderResp resp = new QueryOrderResp();
		TreeMap<String, String> map = new TreeMap<String, String>();
		map.put("merchantNo", MERCHANT_NO);
		map.put("orderNo", order.getOrderNo());
		String signStr = postString(map);
		map.put("sign", FSMD5.codeFor(signStr + KEY).toUpperCase());
		String content = FSString.convertMapToUrlParameter(map);
		FSLog.api.info("提交到WMYL交易订单查询数据：" + content);
		try {
			String result = FSHttp.postFormString(TRADE_QUERY_URL, content, "UTF-8");
			FSLog.api.info("WMYL交易订单查询返回数据：" + result);
			if(StrKit.notBlank(result)) {
				resp.setCodeAndMsg(Resp.Success.getCode(), Resp.Success.getMsg());
				JSONObject obj = JSONObject.parseObject(result);
				String respCode = obj.getString("respCode");
				if ("0000".equals(respCode)) {
					String payStatus = obj.getString("orderStatus");
					if ("PAY_FINISHED".equals(payStatus) || "TRADE_FINISHED".equals(payStatus)) {
						order.setOrderStatus(OrderStatus.Success.getValue());
						resp.setOriginalRespCode(Resp.Success.getCode());
						resp.setOriginalRespMsg(Resp.Success.getMsg());
					} else if("WAIT_PAY".equals(payStatus)) {
						order.setOrderStatus(OrderStatus.InProcess.getValue());
						resp.setOriginalRespCode(Resp.InProcess.getCode());
						resp.setOriginalRespMsg(Resp.InProcess.getMsg());
					} else {
						order.setOrderStatus(OrderStatus.Fail.getValue());
						resp.setOriginalRespCode(Resp.Fail.getCode());
						resp.setOriginalRespMsg(Resp.Fail.getMsg());
					}
					order.update();
				}
			}
		} catch(Exception e) {
			FSLog.api.error("WMYL交易查询异常:" + e);
			resp.setCodeAndMsg(Resp.InProcess.getCode(), Resp.InProcess.getMsg());
		}
		return resp;
	}

	@Override
	public DFResp df(DFReq req, TradeOrder order) throws Exception {
		DFResp rsp = new DFResp(req);
		TreeMap<String, String> map = new TreeMap<String, String>();
		map.put("merchantNo", MERCHANT_NO);
		map.put("payNo", order.getOrderNo());
		map.put("amount", order.getAmount().toString());
		map.put("accNo", req.getAccountCardNo());
		map.put("accName", req.getAccountName());
		map.put("acqCode", "8099");
		map.put("openBank", req.getBankName());
		map.put("province", req.getProvince());
		map.put("city", req.getCity());
		map.put("bankBranch", req.getBranchName());
		map.put("notifyurl", DF_NOTIFY_URL);
		String bankCode = BankCode.getBankCode(req.getBankName());
		if(StrKit.isBlank(bankCode)) {
			bankCode = "";
		}
		map.put("bankCode", bankCode);
		String signStr = postString(map);
		map.put("sign", FSMD5.codeFor(signStr + KEY).toUpperCase());
		String content = FSString.convertMapToUrlParameter(map);
		FSLog.api.info("提交到WMYL代付数据：" + content);
		try {
			String result = FSHttp.postFormString(DF_URL, content, "UTF-8");
			FSLog.api.info("WMYL响应：" + result);
			JSONObject returnObj = JSONObject.parseObject(result);
			String retcode = returnObj.getString("retcode");
			if ("0000".equals(retcode)) {
				rsp.setCodeAndMsg(Resp.Success.getCode(), Resp.Success.getMsg());
			} else {
				rsp.setCodeAndMsg(Resp.InProcess.getCode(), Resp.InProcess.getMsg());
			}
		} catch (Exception e) {
			FSLog.api.error(e);
			rsp.setCodeAndMsg(Resp.InProcess.getCode(), Resp.InProcess.getMsg());
		}
		return rsp;
	}
	
	@Override
	public QueryOrderResp dfQuery(TradeOrder order) throws Exception {
		QueryOrderResp resp = new QueryOrderResp();
		TreeMap<String, String> map = new TreeMap<String, String>();
		map.put("merchantNo", MERCHANT_NO);
		map.put("payNo", order.getOrderNo());
		String signStr = postString(map);
		map.put("sign", FSMD5.codeFor(signStr + KEY).toUpperCase());
		String content = FSString.convertMapToUrlParameter(map);
		FSLog.api.info("提交到WMYL代付订单查询数据：" + content);
		try {
			String result = FSHttp.postFormString(DF_QUERY_URL, content, "UTF-8");
			FSLog.api.info("WMYL代付订单查询返回数据：" + result);
			if(StrKit.notBlank(result)) {
				resp.setCodeAndMsg(Resp.Success.getCode(), Resp.Success.getMsg());
				JSONObject obj = JSONObject.parseObject(result);
				String respCode = obj.getString("respCode");
				if ("0000".equals(respCode)) {
					String payStatus = obj.getString("payStatus");
					if ("00000".equals(payStatus)) {
						order.setOrderStatus(OrderStatus.Success.getValue());
						resp.setOriginalRespCode(Resp.Success.getCode());
						resp.setOriginalRespMsg(Resp.Success.getMsg());
					} else if("30000".equals(payStatus)) {
						order.setOrderStatus(OrderStatus.InProcess.getValue());
						resp.setOriginalRespCode(Resp.InProcess.getCode());
						resp.setOriginalRespMsg(Resp.InProcess.getMsg());
					} else {
						order.setOrderStatus(OrderStatus.Fail.getValue());
						resp.setOriginalRespCode(Resp.Fail.getCode());
						resp.setOriginalRespMsg(Resp.Fail.getMsg());
					}
					order.update();
				}
			}
		} catch(Exception e) {
			FSLog.api.error("WMYL查询异常:" + e);
			resp.setCodeAndMsg(Resp.InProcess.getCode(), Resp.InProcess.getMsg());
		}
		return resp;
	}

	@Override
	public QuickPaySetResp quickPaySet(QuickPaySetReq req, TradeOrder order) throws Exception {
		return null;
	}

	@Override
	public QuickPayResp quickPay(QuickPayReq req, TradeOrder order) throws Exception {
		return null;
	}

	@Override
	public SendSMSResp sendSMS(SendSMSReq req) throws Exception {
		return null;
	}

	@Override
	public QueryCardInfoResp queryCardInfo(QueryCardInfoReq req) throws Exception {
		return null;
	}

	@Override
	public RefundResp refund(RefundReq req, TradeOrder refundOrder, TradeOrder orignOrder) throws Exception {
		return null;
	}
	
	public static void main(String[] args) throws Exception {
		SystemConfig sf = new SystemConfig();
		sf.configConstant(new Constants());
//		TreeMap<String, String> reqMap = new TreeMap<String, String>();
//		reqMap.put("merchantNo", "A10100059980145");
//		reqMap.put("orderNo", "D20180918001");
//		reqMap.put("trxAmt", "12345");
//		reqMap.put("productDesc", "商品收银");
//		reqMap.put("bankCode", "CMBC");
//		reqMap.put("notifyUrl", "http://137.59.149.43:8080/notify/kkr");
//		reqMap.put("showUrl", "http://137.59.149.43:8080/notify/kkr");
//		String s = postString(reqMap);
//		System.out.println(s + "B31F69449CF2D253");
//		reqMap.put("sign", FSMD5.codeFor(s + "B31F69449CF2D253").toUpperCase());
//		String reqJsonStr = FSString.convertMapToUrlParameter(reqMap);
//		System.out.println(reqJsonStr);
//		String resultStr = FSHttp.postFormString("http://159.138.6.240:7005/zf811-posp-proxy/ykGateway.app", reqJsonStr, "UTF-8");
//		System.out.println(resultStr);
		
		TreeMap<String, String> reqMap = new TreeMap<String, String>();
		reqMap.put("agentNo", "4800009");
		reqMap.put("acqCode", "8096");
		String s = postString(reqMap);
		System.out.println(s + "B31F69449CF2D253");
		reqMap.put("sign", FSMD5.codeFor(s + "B31F69449CF2D253").toUpperCase());
		String reqJsonStr = postString(reqMap);
		System.out.println(reqJsonStr);
		String resultStr = FSHttp.postFormString("http://159.138.6.240:7005/zf811-posp-proxy/YKQueryBalance.app", reqJsonStr, "UTF-8");
		System.out.println(resultStr);
	}
	
	public static String postString(TreeMap<String, String> map) {
		StringBuffer sb = new StringBuffer();
		for (Entry<String, String> entry : map.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			if (StrKit.notBlank(value) && ("null".equals(value) == false)) {
				sb.append(key + "=" + value + "&");
			}
		}
		sb.deleteCharAt(sb.length() - 1);
		return sb.toString();
	}
	

}
